using System;
using MyReactivity;
using MyReactivity.Abstractions;
using Project.Models;
using Project.ViewModels.Abstractions;
using UnityEngine;

namespace Project.ViewModels
{
    public class ItemViewModel : ViewModelBase<Slot>, IDisposable
    {
        private readonly ItemConfigsStorage _itemConfigsStorage;
        private readonly ReactiveProperty<Sprite> _sprite;
        private readonly ReactiveProperty<string> _quantityText;

        public ItemViewModel(Slot slot, ItemConfigsStorage itemConfigsStorage) : base(slot)
        {
            _itemConfigsStorage = itemConfigsStorage;
            _sprite = new ReactiveProperty<Sprite>();
            _quantityText = new ReactiveProperty<string>();

            IsDragging = new ReactiveProperty<bool>();

            OnItemIdValueChanged(slot.ItemId.Value);
            OnQuantityOfItemsValueChanged(slot.QuantityOfItems.Value);

            Model.ItemId.ValueChanged += OnItemIdValueChanged;
            Model.QuantityOfItems.ValueChanged += OnQuantityOfItemsValueChanged;
        }

        public readonly ReactiveProperty<bool> IsDragging;

        public IReadOnlyReactiveProperty<Sprite> Sprite => _sprite;
        public IReadOnlyReactiveProperty<string> QuantityText => _quantityText;

        public void Dispose()
        {
            Model.ItemId.ValueChanged -= OnItemIdValueChanged;
            Model.QuantityOfItems.ValueChanged -= OnQuantityOfItemsValueChanged;
        }

        private void OnItemIdValueChanged(int newValue) =>
            _sprite.Value = Model.IsEmpty.Value ? null : _itemConfigsStorage[newValue].Sprite;
        private void OnQuantityOfItemsValueChanged(int newValue) =>
            _quantityText.Value = Model.IsEmpty.Value ? string.Empty : newValue.ToString();
    }
}
